<template>
  <div>
    <!-- 三级分类全局组件 -->
    <Category :scene="scene"></Category>
    <!-- 添加属性按钮 -->
    <el-card style="margin: 10px 0">
      <div v-show="scene === 0">
        <el-button
          type="primary"
          icon="Plus"
          :disabled="!categoryStore.c3Id"
          @click="addAttr"
          >添加属性</el-button
        >
        <!-- 属性列表 -->
        <el-table border style="margin: 10px 0" :data="attrArr">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="120px"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="200px"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-tag
                v-for="(item, index) in row.attrValueList"
                :key="item.id"
                style="margin-right: 5px"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template #="{ row, $index }">
              <!-- 修改属性按钮 -->
              <el-button
                type="warning"
                size="small"
                icon="Edit"
                @click="updateAttr(row)"
              ></el-button>
              <!-- 删除属性按钮 -->

              <el-popconfirm
                :title="`确定删除${row.attrName}吗?`"
                width="200px"
                @confirm="deleteAttr(row.id)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加属性值的表格 -->
      <div v-show="scene === 1">
        <!-- 展示添加属性与修改数据的结构 -->
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              placeholder="请输入属性名称"
              v-model="attrParams.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          :disabled="!attrParams.attrName"
          type="primary"
          icon="Plus"
          @click="addAttrValue"
        >
          添加属性值</el-button
        >
        <el-button plain @click="cancel">取消</el-button>
        <el-table
          border
          style="margin: 10px 0"
          :data="attrParams.attrValueList"
        >
          <el-table-column
            width="80px"
            type="index"
            align="center"
            label="序号"
          >
          </el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-input
                v-if="row.flag"
                size="small"
                placeholder="请输入属性值名称"
                v-model="row.valueName"
                @blur="toLook(row, $index)"
                :ref="(vc: any) => (inputArr[$index] = vc)"
              ></el-input>
              <el-tag @click="toEdit(row, $index)" v-else>{{
                row.valueName
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="attrParams.attrValueList.splice($index, 1)"
              >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button :disabled="!attrParams.attrName" type="primary" @click="save"
          >保存</el-button
        >
        <el-button plain @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { watch, ref, reactive, nextTick, onBeforeUnmount } from "vue";
// 引入获取属性与属性值接口方法
import { reqAttr, reqAddOrUpdateAttr, reqDeleteAttr } from "@/api/product/attr";
import type {
  AttrResponseData,
  AttrList,
  Attr,
  AttrValue,
} from "@/api/product/attr/type";
// 获取分类小仓库
import useCategoryStore from "@/store/modules/category";
import { ElMessage } from "element-plus";
const categoryStore = useCategoryStore();

// 存储已有属性值
const attrArr = ref<AttrList>([]);
// 定义card组件内容切换变量
const scene = ref<number>(0); // 0:table 1:添加与修改
// 收集新增属性的数据
const attrParams = reactive<Attr>({
  attrName: "", // 新增属性的名字
  attrValueList: [], // 新增的属性值数组
  categoryId: "", // 三级分类的ID
  categoryLevel: 3,
});
// 定义数组存储对应组件实例el-input
const inputArr = ref<any>([]);

// 监听三级分类id变化
watch(
  () => categoryStore.c3Id,
  () => {
    // 清空上一次查询的属性与属性值
    attrArr.value = [];
    // 保证有三级分类id 才去发送id
    if (!categoryStore.c3Id) {
      return;
    }
    getAttr();
  }
);

// 获取属性值方法
const getAttr = async () => {
  // 结构id
  const { c1Id, c2Id, c3Id } = categoryStore;
  const res: AttrResponseData = await reqAttr(
    c1Id as number,
    c2Id as number,
    c3Id as number
  );
  if (res.code === 200) {
    attrArr.value = res.data;
    console.log(attrArr.value);
  }
};

// 添加属性按钮回调
const addAttr = () => {
  // 清空表单
  Object.assign(attrParams, {
    attrName: "", // 新增属性的名字
    attrValueList: [], // 新增的属性值数组
    categoryId: categoryStore.c3Id, // 三级分类的ID
    categoryLevel: 3,
  });
  // 切换为添加属性页面
  scene.value = 1;
};

// 修改属性按钮回调
const updateAttr = (row: Attr) => {
  scene.value = 1;
  // 将已有的属性对象赋值给attrParams
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
};

// 删除属性按钮的回调
const deleteAttr = async (attrId: number) => {
  const res = await reqDeleteAttr(attrId);
  if (res.code === 200) {
    ElMessage.success("删除成功");
    getAttr();
  } else {
    ElMessage.error("删除失败");
  }
};

// 取消按钮的回调
const cancel = () => {
  scene.value = 0;
  // 重新渲染页面
  getAttr();
};

// 添加属性值2按钮的回调
const addAttrValue = () => {
  // 点击按钮时,向数组添加一个属性值对象
  attrParams.attrValueList.push({
    valueName: "",
    flag: true, // 控制每一个属性值的编辑模式和切换模式
  });

  // 最后一个input组件自动聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};

// 保存按钮的回调
const save = async () => {
  if (attrParams.attrValueList.length !== 0) {
    // 发送请求
    const res = await reqAddOrUpdateAttr(attrParams);
    if (res.code === 200) {
      scene.value = 0;
      // 提示信息
      ElMessage.success(attrParams.id ? "修改成功" : "添加成功");
      // 重新渲染页面
      getAttr();
    } else {
      ElMessage.error(attrParams.id ? "修改失败" : "添加失败");
    }
  } else {
    ElMessage.error("请输入属性值");
  }
};

// 添加属性值表单元素失去焦点回调
const toLook = (row: AttrValue, $index: number) => {
  // 非法情况的判断
  if (!row.valueName.trim()) {
    // 删除属性值为空的元素
    attrParams.attrValueList.splice($index, 1);
    ElMessage.error("属性值不能为空");
    return;
  }
  // 属性值相同的时候
  const repeat = attrParams.attrValueList.find((item) => {
    // 将当前正在添加的属性值从row中去除
    if (item != row) {
      return item.valueName == row.valueName;
    }
  });

  if (repeat) {
    // 将重复的属性值直接删掉
    attrParams.attrValueList.splice($index, 1);
    // 错误提示信息
    ElMessage.error("属性值不能重复");
    return;
  }
  row.flag = !row.flag;
};

const toEdit = (row: AttrValue, $index: number) => {
  row.flag = !row.flag;

  // 响应式数据发生变化,获取更新后的DOM实例
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};

// 路由组件销毁的时候 清空仓库的数据
onBeforeUnmount(() => {
  categoryStore.$reset();
});
</script>

<style scoped></style>
